<template>
  <el-dialog
    class="base-dialog-root"
    :model-value="visible"
    width="920"
    title="创建活动"
    @close="onClose"
  >
    <div class="new-form">
      <div class="new-form-left">
        <el-anchor
          direction="vertical"
          type="default"
          :offset="30"
        > 
        <el-anchor-link class="survertype-item" 
          @click="onBusineTypeChange('')"
         :class="{ active: busineType === '' }" 
         title="全部">
         全部
        </el-anchor-link>
          <el-anchor-link class="survertype-item" 
          @click="onBusineTypeChange(bis.id)"
          :class="{ active: busineType === bis.id }"
          v-for="(bis, index) in templateMenus" 
          :key="index" 
          :title="bis.name">
          <SvgIcon class="x16" :name="bis.icon"></SvgIcon>
          {{ bis.name }}
        </el-anchor-link>
        </el-anchor>
      </div>
      <div class="new-form-right">
        <ul class="new-cardList" id="formid">
          <li
            class="list-item"
            @click="onSelectTypeChange('')"
          >
            <img class="img" src="@assets/images/normal-icon.webp" alt="类别图片" />
            <div class="container">
              <div class="title-container">
                <p class="title">空白收集</p>
              </div>
            </div>
          </li>
        </ul>

        <div class="new-cardpanel" v-for="(item, index) in templateList" :key="index">
          <div class="list-type" :id="'form'+item.idkey">{{ item.idname }}</div>
          <ul class="new-cardList">
            <li
              v-for="(itm, idx) in item.list"
              class="list-newitem"
              :key="idx"
              @click="onSelectTempChange(itm)"
            >
              <div class="list-top">
                <img class="xfolder-table mr-step" src="@assets/images/fileform.webp" alt="" />
                <div class="title">{{ itm.formName }}</div>
              </div>
              <div class="container">
                <template v-if="itm.listConf">
                  <template v-for="(ritm, ridx) in itm.listConf.split(',')">
                    <p class="desc"  :key="ridx" v-if="ridx < 3">
                      <span v-html="ritm"></span>
                    </p>
                  </template>
                </template>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <template #footer>
 
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')

import { save as createForm, list as getTemplates, copy as copyForm } from '@/management/api/dataform'
import {
  surveyTypeSelect
} from '@/management/config/formsConfig'
import { FormType, templateMenus } from '@/management/utils/types/formsTypes';
import SvgIcon from '@common/SvgIcon/index.vue'

// import { SURVEY_TYPE_LIST } from './types'
// const renderData = computed(() => SURVEY_TYPE_LIST)
const router = useRouter()
const store = useStore()

const selectType = ref<string>('')
const busineType = ref<string>('')
const now = new Date().getTime()
const templateList = ref<any[]>([])

const workSpaceId = computed(() => {
  return store.state.dataform.workSpaceId
})

const state = reactive({
  rules: {
    title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }]
  },
  canSubmit: true,
  form: {
    busineType: '1',
    dataFormAttributeList: [],
    endTime: moment((now + 604800000)).format('yyyy-MM-DD HH:mm'),
    formName: '请输入活动名称',
    formRemark: '请输入活动说明',
    formType: FormType.Forms,
    isDel: '1',
    isLogin: '1',
    isMultiple: '1',
    isTop: '1',
    isUpdate: '1',
    parentId: workSpaceId.value || '-1',
    roleType: '1',
    startTime: moment(now).format('YYYY-MM-DD HH:mm'),
    status: '1',
    useLimit: '1'
  }
})


const emit = defineEmits(['on-close-codify'])
const props = defineProps({
  visible: Boolean
})
const onSelectTypeChange = (type: string) => {
  selectType.value = type

  onConfirm()
}
const onBusineTypeChange = (type: string) => {
  busineType.value = type
  let target = type ? '#form' + type : '#formid'
  const element = document.querySelector(target);
  console.log(element);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
}

const onClose = () => {
  state.form = {
    busineType: '1',
    dataFormAttributeList: [],
    endTime: '',
    formName: '请输入活动名称',
    formRemark: '请输入活动说明',
    formType: FormType.Forms,
    isDel: '',
    isLogin: '',
    isMultiple: '',
    isTop: '',
    isUpdate: '',
    parentId: '-1',
    roleType: '',
    startTime: '',
    status: '',
    useLimit: ''
  }
  // 清空空间详情
  emit('on-close-codify')
}

const onCopy = async (data: any) => {
  // try {
    const res: any = await copyForm({
      formId: data._id,
      formType: FormType.Forms, 
    })

    if (res?.serverResult?.resultCode === '200') {
      const { formId } = res.result
      router.push({
        name: 'FormsEditIndex',
        params: {
          id: formId
        },
        query: {
          tid: data._id
        }
      })
    } else {
      ElMessage.error(res?.serverResult?.resultMessage)
    }
  // } catch (err) {
  //   ElMessage.error(err)
  // }
}
const onSelectTempChange = (item: Object) => {
  onCopy(item)
}

const onConfirm = async () => {
  if (!state.canSubmit) {
    return
  }
  state.canSubmit = false
  const payload: any = {
    ...state.form
  }
  if (store.state.dataform.workSpaceId) {
    payload.workspaceId = store.state.dataform.workSpaceId
  }

  const res: any = await createForm(payload)
  
  if (res?.serverResult?.resultCode === '200' && res?.result?.formId) {
    const id = res.result.formId
    store.commit('editform/setFormId', id)
    store.commit('editform/clearSchema')
    setTimeout(() => {
      router.push({
        name: 'FormsEditIndex',
        params: {
          id
        }
      })
    }, 500)
   
  } else {
    ElMessage.error(res?.serverResult?.resultMessage || '创建失败')
  }
  state.canSubmit = true

  emit('on-close-codify', 'update')
}

const getTemplateList = async () => {
  let condition = {
        formType: FormType.System
      }

      try {
        let params = {
          pageNo: 1,
          pageSize: 1000, // 默认一页10条
          orderList: ['busineType asc'],
          condition: condition
        }

        templateList.value = []
        const res: any = await getTemplates(params)
        if (res?.serverResult.resultCode === '200') {
          let originlist = (res?.result?.list || [])
          let tlist: any = []
          originlist.forEach((item: any, index: any) => {
            let tmp = {
              _id: item.formId,
              ...item
            }
            if (index === 0) {
              tmp.idkey = item.busineType
              tmp.idname = surveyTypeSelect.value.find((itm: any) => itm.value === item.busineType)?.label

              tlist.push(tmp)
            } else if (originlist[index - 1].busineType !== item.busineType) {
              templateList.value.push({
                idkey: tlist[0].idkey,
                idname: tlist[0].idname,
                list: [...tlist]
              })
              tlist = []

              tmp.idkey = item.busineType
              tmp.idname = surveyTypeSelect.value.find((itm: any) => itm.value === item.busineType)?.label
              tlist.push(tmp)
            } else {
              tmp.idkey = item.busineType
              tmp.idname = surveyTypeSelect.value.find((itm) => itm.value === item.busineType)?.label

              tlist.push(tmp)
            }

            if (index > 0 && index === originlist.length - 1) {
              templateList.value.push({
                idkey: tlist[0].idkey,
                idname: tlist[0].idname,
                list: [...tlist]
              })
            }
          }) || []
        } else {
          ElMessage.error(res.serverResult.resultMessage)
        }
      } catch (error) {
        console.log(error)
      }
}

watch(
  () => props.visible,
  (val) => {
    if (val) {
      getTemplateList()
    }
  },{
    immediate: true
  }
)
</script>
<style>
.base-dialog-root {
  border-radius: 12px;
}
</style>
<style lang="scss" scoped>
.new-form {
  display: flex;
  width: 100%;
  height: 100%;
  min-height: 500px;
  position: relative;

  .new-form-left {
    width: 150px;
    height: 100%;
    max-height: 60vh;
    overflow-y: auto;
    border-right: 1px solid #ECECEC;
    position: absolute;

    :deep(.el-anchor__marker) {
      display: none;
    }
    :deep(.el-anchor.el-anchor--vertical .el-anchor__list) {
      --el-anchor-padding-indent: 0;
    }
  }
  .new-form-right {
    margin-left: 10px;
    max-height: 60vh;
    overflow-y: auto;
    width: calc(100% - 160px);
    margin-left: 160px;
  }

  .survertype-item {
    padding: 1px 15px;
    border-radius: 4px;
    cursor: pointer;
    margin-right: 10px;

    &:hover,
    &.active {
      background: #DFF0FF;
    }
  }
  .survertype-item + .survertype-item {
    margin-top: 10px;
  }
}
.new-cardpanel {
  background: #FBFBFB;
  border-radius: 12px;
  padding: 10px 15px;
  margin-bottom: 20px;

  .list-type {
    font-size: 14px;
    color: #333;
    margin-bottom: 15px;
  }
}
.new-cardList {
  display: flex;
  flex-wrap: wrap;
  width: 100%;

  .list-item {
    width: calc(25% - 12px);
    height: 62px;
    margin-bottom: 16px;
    border-radius: 2px;
    padding: 33px 0;
    position: relative;
    cursor: pointer;
    display: flex;
    align-items: center;
    box-sizing: border-box;
    background: #FFFFFF;
    box-shadow: 0px 6px 8px 1px rgba(0,0,0,0.06);
    border-radius: 6px 6px 6px 6px;
    border: 1px solid #E8E8E8;

    .img {
      margin-left: 12px;
      width: 31px;
      height: 29px;
      // border: 1px solid #FFD166;
      background-color: $primary-color-hover;
      border-radius: 100%;
      z-index: 1;
    }

    .container {
      display: flex;
      flex-direction: column;
      margin-left: 12px;
      z-index: 1;

      .title-container {
        display: flex;
      }
    }

    .title {
      color: $font-color-title;
      font-size: 16px;
      font-family: PingFangSC-Regular;
    }

    .desc {
      font-size: 12px;
      color: $font-color;
    }
  }

  .list-item + .list-item {
    margin-left: 16px;
  }

  .list-item:nth-child(4n + 1) {
    margin-left: 0;
  }

  .list-newitem {
    width: calc(25% - 12px);
    height: 142px;
    margin-bottom: 16px;
    border-radius: 2px;
    padding: 15px 5px 5px 5px;
    position: relative;
    cursor: pointer;
    
    box-sizing: border-box;
    background: #FFFFFF;
    box-shadow: 0px 6px 8px 1px rgba(0,0,0,0.06);
    border-radius: 6px 6px 6px 6px;
    border: 1px solid #E8E8E8;

    .list-top {
      display: flex;
      align-items: center;
    }
    .list-top .title {
      white-space: nowrap;
      text-overflow: ellipsis;
      width: 100%;
      overflow: hidden;
    }

    .img {
      margin: 0 10px;
      width: 31px;
      height: 29px;
      // border: 1px solid #FFD166;
      background-color: $primary-color-hover;
      border-radius: 100%;
      z-index: 1;
    }

    .container {
      display: flex;
      flex-direction: column;
      margin-top: 10px;
      padding: 10px;
      height: 75px;
      overflow: hidden;
      color: #999;
      font-size: 12px;
      line-height: 22px;

      .title-container {
        display: flex;
      }

      .desc {
        width: 100%;
        height: 28px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        position: relative;
        padding-left: 12px;
      }
      .desc::before {
        left: 0px;
        top: 8px;
        content: ' ';
        display: inline-block;
        width: 4px;
        height: 4px;
        background: #e6e8eb;
        border-radius: 50%;
        position: absolute;
      }
    }

    .title {
      color: $font-color-title;
      font-size: 12px;
      font-family: PingFangSC-Regular;
    }
  }

  .list-newitem + .list-newitem {
    margin-left: 16px;
  }

  .list-newitem:nth-child(4n + 1) {
    margin-left: 0;
  }
}
</style>
